#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use chrono::{NaiveDate,NaiveDateTime};
use crate::{custcontroller::goods_cust_controller::remove_goods, domain::CustOrderBean};
use crate::domain::CustOrderQueryRequest;
use crate::domain::my_date_format::DATE_FORMAT;
use crate::domain::my_date_time_format::DATE_TIME_FORMAT;
use crate::serviceimpl::cust_order_service::activate_all_cust_orders as service_activate_all_cust_orders;
use crate::serviceimpl::cust_order_service::activate_cust_order as service_activate_cust_order;
use crate::serviceimpl::cust_order_service::add_cust_order as service_add_cust_order;
use crate::serviceimpl::cust_order_service::clone_all_cust_orders as service_clone_all_cust_orders;
use crate::serviceimpl::cust_order_service::clone_cust_order as service_clone_cust_order;
use crate::serviceimpl::cust_order_service::count_search_cust_orders_by_fields_records as service_count_search_cust_orders_by_fields_records;
use crate::serviceimpl::cust_order_service::delete_all_cust_orders as service_delete_all_cust_orders;
use crate::serviceimpl::cust_order_service::delete_cust_order as service_delete_cust_order;
use crate::serviceimpl::cust_order_service::find_cust_order_by_id as service_find_cust_order_by_id;
use crate::serviceimpl::cust_order_service::find_cust_order_by_name as service_find_cust_order_by_name;
use crate::serviceimpl::cust_order_service::list_active_cust_orders as service_list_active_cust_orders;
use crate::serviceimpl::cust_order_service::list_all_cust_orders as service_list_all_cust_orders;
use crate::serviceimpl::cust_order_service::search_cust_orders_by_fields as service_search_cust_orders_by_fields;
use crate::serviceimpl::cust_order_service::search_cust_orders_by_fields_by_page as service_search_cust_orders_by_fields_by_page;
use crate::serviceimpl::cust_order_service::soft_delete_all_cust_orders as service_soft_delete_all_cust_orders;
use crate::serviceimpl::cust_order_service::soft_delete_cust_order as service_soft_delete_cust_order;
use crate::serviceimpl::cust_order_service::toggle_cust_order as service_toggle_cust_order;
use crate::serviceimpl::cust_order_service::toggle_one_cust_order as service_toggle_one_cust_order;
use crate::serviceimpl::cust_order_service::update_cust_order as service_update_cust_order;
use crate::serviceimpl::pay_type_service::find_pay_type_by_id as service_find_pay_type_by_id;
use crate::serviceimpl::status_service::find_status_by_id as service_find_status_by_id;
use crate::serviceimpl::user_service::find_user_by_id as service_find_user_by_id;
use crate::serviceimpl::order_item_service::list_my_order_items as service_list_my_order_items;
use crate::utils::excel_util::export_excel_workbook_with_image;
use crate::utils::pdf_util::export_pdf_with_images;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::fs;
use tower_http::{trace::TraceLayer};

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustOrderRequest {
	pub id: Option<i64>,
	pub name: Option<String>,
	pub active: Option<bool>,
	pub total: Option<f64>,
	pub amount: Option<i32>,
	pub status_id: Option<i64>,
	pub pay_type_id: Option<i64>,
	pub phone: Option<String>,
	pub address: Option<String>,
	pub order_date_time: Option<String>,
	pub user_id: Option<i64>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdsRequest {
	pub ids: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderItemRequest {
	pub id: Option<i64>,
	pub name: Option<String>,
	pub active: Option<bool>,
	pub price: Option<f64>,
	pub amount: Option<i32>,
	pub goods_id: Option<i64>,
	pub cust_order_id: Option<i64>,
}

pub fn cust_order_controller() -> Router {
	Router::new()
	.route("/listAllCustOrders", post(list_all_cust_orders))
	.route("/updateCustOrder", post(update_cust_order))
	.route("/deleteCustOrder", post(delete_cust_order))
	.route("/addCustOrder", post(add_cust_order))
	.route("/softDeleteCustOrder", post(soft_delete_cust_order))
	.route("/findCustOrderById", post(find_cust_order_by_id))
	.route("/findCustOrderByName", post(find_cust_order_by_name))
	.route("/listActiveCustOrders", post(list_active_cust_orders))
	.route("/deleteAllCustOrders", post(delete_all_cust_orders))
	.route("/softDeleteAllCustOrders", post(soft_delete_all_cust_orders))
	.route("/toggleCustOrder", post(toggle_cust_order))
	.route("/toggleOneCustOrder", post(toggle_one_cust_order))
	.route("/searchCustOrdersByFieldsByPage", post(search_cust_orders_by_fields_by_page))
	.route("/activateCustOrder", post(activate_cust_order))
	.route("/activateAllCustOrders", post(activate_all_cust_orders))
	.route("/exportCustOrders", get(export_cust_orders))
	.route("/exportCustOrdersPDF", get(export_cust_orders_pdf))
	.route("/filterCustOrdersExcel", get(filter_cust_orders_excel))
	.route("/filterCustOrdersPDF", get(filter_cust_orders_pdf))
	.route("/cloneCustOrder", post(clone_cust_order))
	.route("/cloneAllCustOrders", post(clone_all_cust_orders))
	.route("/checkAccessCustOrder", get(check_access_cust_order))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}
pub async fn activate_all_cust_orders(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_activate_all_cust_orders(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn activate_cust_order(Form(cust_order_request):Form<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let _result = service_activate_cust_order(id).await;
	match _result {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn add_cust_order(Json(cust_order_request):Json<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let name = cust_order_request.name.unwrap_or_default();
	let active = cust_order_request.active.unwrap_or_default();
	let total = cust_order_request.total.unwrap_or_default();
	let amount = cust_order_request.amount.unwrap_or_default();
	let status_id = cust_order_request.status_id.unwrap_or_default();
	let pay_type_id = cust_order_request.pay_type_id.unwrap_or_default();
	let phone = cust_order_request.phone.unwrap_or_default();
	let address = cust_order_request.address.unwrap_or_default();
	let order_date_time = cust_order_request.order_date_time.unwrap_or_default();
	let mut _fmt_order_date_time = Option::None;
	if order_date_time != "" {
		_fmt_order_date_time = Some(NaiveDateTime::parse_from_str(&order_date_time,DATE_TIME_FORMAT).unwrap());
	}
	let user_id = cust_order_request.user_id.unwrap_or_default();

	let cust_order = CustOrderBean{
	id : id,
	name : name,
	active : active,
	total : total,
	amount : amount,
	status_id : status_id,
	pay_type_id : pay_type_id,
	phone : phone,
	address : address,
	order_date_time : _fmt_order_date_time,
	user_id : user_id,
	};

	let _result = service_add_cust_order(cust_order).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn check_access_cust_order() ->String {
	r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn clone_all_cust_orders(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_clone_all_cust_orders(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn clone_cust_order(Form(cust_order_request):Form<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let _result = service_clone_cust_order(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_all_cust_orders(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_delete_all_cust_orders(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_cust_order(Form(cust_order_request):Form<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let _result = service_delete_cust_order(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn export_cust_orders() ->Response<Body> {
	let list = service_list_all_cust_orders().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "订单信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"总价".to_string(),"商品总数".to_string(),"状态".to_string(),"支付方式".to_string(),"电话".to_string(),"地址".to_string(),"日期时间".to_string(),"用户".to_string()];
	let is_images = vec![false,false,false,false,false,false,false,false,false,false,false];
	for cust_order in list {
		let status_id = cust_order.status_id;
		let mut status_id_name0 = "".to_string();
		if status_id > 0 {
			let status_id_type0 = service_find_status_by_id(status_id).await.unwrap();
			if status_id_type0.id != 0 {
				status_id_name0 = status_id_type0.name;
			}
		}
		let pay_type_id = cust_order.pay_type_id;
		let mut pay_type_id_name0 = "".to_string();
		if pay_type_id > 0 {
			let pay_type_id_type0 = service_find_pay_type_by_id(pay_type_id).await.unwrap();
			if pay_type_id_type0.id != 0 {
				pay_type_id_name0 = pay_type_id_type0.name;
			}
		}
		let mut _fmt_order_date_time = "".to_string();
		match cust_order.order_date_time {
			Some(order_date_time) => _fmt_order_date_time = format!("{}", order_date_time.format(DATE_TIME_FORMAT)),
			None => _fmt_order_date_time = "".to_string(),
		}
		let user_id = cust_order.user_id;
		let mut user_id_name0 = "".to_string();
		if user_id > 0 {
			let user_id_type0 = service_find_user_by_id(user_id).await.unwrap();
			if user_id_type0.id != 0 {
				user_id_name0 = user_id_type0.user_name;
			}
		}

		let row = vec![cust_order.id.to_string(),cust_order.name,cust_order.active.to_string(),cust_order.total.to_string(),cust_order.amount.to_string(),status_id_name0,pay_type_id_name0,cust_order.phone,cust_order.address,_fmt_order_date_time,user_id_name0];
		contents.push(row);
	}

	let full_file_path = "./template/temp/custOrders.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);


	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=custOrders.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn export_cust_orders_pdf() ->Response<Body> {
	let list = service_list_all_cust_orders().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "订单信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"总价".to_string(),"商品总数".to_string(),"状态".to_string(),"支付方式".to_string(),"电话".to_string(),"地址".to_string(),"日期时间".to_string(),"用户".to_string()];
	let is_images = vec![false,false,false,false,false,false,false,false,false,false,false];
	for cust_order in list {
		let status_id = cust_order.status_id;
		let mut status_id_name0 = "".to_string();
		if status_id > 0 {
			let status_id_type0 = service_find_status_by_id(status_id).await.unwrap();
			if status_id_type0.id != 0 {
				status_id_name0 = status_id_type0.name;
			}
		}
		let pay_type_id = cust_order.pay_type_id;
		let mut pay_type_id_name0 = "".to_string();
		if pay_type_id > 0 {
			let pay_type_id_type0 = service_find_pay_type_by_id(pay_type_id).await.unwrap();
			if pay_type_id_type0.id != 0 {
				pay_type_id_name0 = pay_type_id_type0.name;
			}
		}
		let mut _fmt_order_date_time = "".to_string();
		match cust_order.order_date_time {
			Some(order_date_time) => _fmt_order_date_time = format!("{}", order_date_time.format(DATE_TIME_FORMAT)),
			None => _fmt_order_date_time = "".to_string(),
		}
		let user_id = cust_order.user_id;
		let mut user_id_name0 = "".to_string();
		if user_id > 0 {
			let user_id_type0 = service_find_user_by_id(user_id).await.unwrap();
			if user_id_type0.id != 0 {
				user_id_name0 = user_id_type0.user_name;
			}
		}

		let row = vec![cust_order.id.to_string(),cust_order.name,cust_order.active.to_string(),cust_order.total.to_string(),cust_order.amount.to_string(),status_id_name0,pay_type_id_name0,cust_order.phone,cust_order.address,_fmt_order_date_time,user_id_name0];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=custOrders.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_cust_orders_excel(Query(cust_order_query_request):Query<CustOrderQueryRequest>) ->Response<Body> {
	let list = service_search_cust_orders_by_fields(cust_order_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "订单信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"总价".to_string(),"商品总数".to_string(),"状态".to_string(),"支付方式".to_string(),"电话".to_string(),"地址".to_string(),"日期时间".to_string(),"用户".to_string()];
	let is_images = vec![false,false,false,false,false,false,false,false,false,false,false];
	for cust_order in list {
		let status_id = cust_order.status_id;
		let mut status_id_name0 = "".to_string();
		if status_id > 0 {
			let status_id_type0 = service_find_status_by_id(status_id).await.unwrap();
			if status_id_type0.id != 0 {
				status_id_name0 = status_id_type0.name;
			}
		}
		let pay_type_id = cust_order.pay_type_id;
		let mut pay_type_id_name0 = "".to_string();
		if pay_type_id > 0 {
			let pay_type_id_type0 = service_find_pay_type_by_id(pay_type_id).await.unwrap();
			if pay_type_id_type0.id != 0 {
				pay_type_id_name0 = pay_type_id_type0.name;
			}
		}
		let mut _fmt_order_date_time = "".to_string();
		match cust_order.order_date_time {
			Some(order_date_time) => _fmt_order_date_time = format!("{}", order_date_time.format(DATE_TIME_FORMAT)),
			None => _fmt_order_date_time = "".to_string(),
		}
		let user_id = cust_order.user_id;
		let mut user_id_name0 = "".to_string();
		if user_id > 0 {
			let user_id_type0 = service_find_user_by_id(user_id).await.unwrap();
			if user_id_type0.id != 0 {
				user_id_name0 = user_id_type0.user_name;
			}
		}

		let row = vec![cust_order.id.to_string(),cust_order.name,cust_order.active.to_string(),cust_order.total.to_string(),cust_order.amount.to_string(),status_id_name0,pay_type_id_name0,cust_order.phone,cust_order.address,_fmt_order_date_time,user_id_name0];
		contents.push(row);
	}

	let full_file_path = "./template/temp/custOrders.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);


	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=custOrders.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_cust_orders_pdf(Query(cust_order_query_request):Query<CustOrderQueryRequest>) ->Response<Body> {
	let list = service_search_cust_orders_by_fields(cust_order_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "订单信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"总价".to_string(),"商品总数".to_string(),"状态".to_string(),"支付方式".to_string(),"电话".to_string(),"地址".to_string(),"日期时间".to_string(),"用户".to_string()];
	let is_images = vec![false,false,false,false,false,false,false,false,false,false,false];
	for cust_order in list {
		let status_id = cust_order.status_id;
		let mut status_id_name0 = "".to_string();
		if status_id > 0 {
			let status_id_type0 = service_find_status_by_id(status_id).await.unwrap();
			if status_id_type0.id != 0 {
				status_id_name0 = status_id_type0.name;
			}
		}
		let pay_type_id = cust_order.pay_type_id;
		let mut pay_type_id_name0 = "".to_string();
		if pay_type_id > 0 {
			let pay_type_id_type0 = service_find_pay_type_by_id(pay_type_id).await.unwrap();
			if pay_type_id_type0.id != 0 {
				pay_type_id_name0 = pay_type_id_type0.name;
			}
		}
		let mut _fmt_order_date_time = "".to_string();
		match cust_order.order_date_time {
			Some(order_date_time) => _fmt_order_date_time = format!("{}", order_date_time.format(DATE_TIME_FORMAT)),
			None => _fmt_order_date_time = "".to_string(),
		}
		let user_id = cust_order.user_id;
		let mut user_id_name0 = "".to_string();
		if user_id > 0 {
			let user_id_type0 = service_find_user_by_id(user_id).await.unwrap();
			if user_id_type0.id != 0 {
				user_id_name0 = user_id_type0.user_name;
			}
		}

		let row = vec![cust_order.id.to_string(),cust_order.name,cust_order.active.to_string(),cust_order.total.to_string(),cust_order.amount.to_string(),status_id_name0,pay_type_id_name0,cust_order.phone,cust_order.address,_fmt_order_date_time,user_id_name0];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=custOrders.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn find_cust_order_by_id(Form(cust_order_request):Form<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let cust_order = service_find_cust_order_by_id(id).await;
	match cust_order {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(cust_order) => {
			let json = serde_json::to_string_pretty(&cust_order).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn find_cust_order_by_name(Form(cust_order_request):Form<CustOrderRequest>) ->String {
	let name = cust_order_request.name.unwrap_or_default();
	let cust_order = service_find_cust_order_by_name(name).await;
	match cust_order {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(cust_order) => {
			let json = serde_json::to_string_pretty(&cust_order).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_active_cust_orders() ->String {
	let cust_orders = service_list_active_cust_orders().await;
	match cust_orders {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(cust_orders) => {
			let json = serde_json::to_string_pretty(&cust_orders).unwrap();
			//println!("{}", json);

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn list_all_cust_orders() ->String {
	let cust_orders = service_list_all_cust_orders().await;
	match cust_orders {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(cust_orders) => {
			let json = serde_json::to_string_pretty(&cust_orders).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn search_cust_orders_by_fields_by_page(Form(cust_order_query_request):Form<CustOrderQueryRequest>) ->String {
	let cust_orders = service_search_cust_orders_by_fields_by_page(cust_order_query_request.clone()).await;
	let total = service_count_search_cust_orders_by_fields_records(cust_order_query_request.clone()).await.unwrap().count_num;
	match cust_orders {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(cust_orders) => {
			let json = serde_json::to_string_pretty(&cust_orders).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("total".to_string(), Value::from(total));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_all_cust_orders(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_soft_delete_all_cust_orders(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_cust_order(Form(cust_order_request):Form<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let _result = service_soft_delete_cust_order(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_cust_order(Form(cust_order_request):Form<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let _result = service_toggle_cust_order(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_one_cust_order(Form(cust_order_request):Form<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let _result = service_toggle_one_cust_order(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn update_cust_order(Json(cust_order_request):Json<CustOrderRequest>) ->String {
	let id = cust_order_request.id.unwrap_or_default();
	let name = cust_order_request.name.unwrap_or_default();
	let active = cust_order_request.active.unwrap_or_default();
	let total = cust_order_request.total.unwrap_or_default();
	let amount = cust_order_request.amount.unwrap_or_default();
	let status_id = cust_order_request.status_id.unwrap_or_default();
	let pay_type_id = cust_order_request.pay_type_id.unwrap_or_default();
	let phone = cust_order_request.phone.unwrap_or_default();
	let address = cust_order_request.address.unwrap_or_default();
	let order_date_time = cust_order_request.order_date_time.unwrap_or_default();
	let mut _fmt_order_date_time = Option::None;
	if order_date_time != "" {
		_fmt_order_date_time = Some(NaiveDateTime::parse_from_str(&order_date_time,DATE_TIME_FORMAT).unwrap());
	}
	let user_id = cust_order_request.user_id.unwrap_or_default();
	let _current_cust_order = service_find_cust_order_by_id(id).await.unwrap();

	let cust_order = CustOrderBean{
	id : id,
	name : name,
	active : active,
	total : total,
	amount : amount,
	status_id : status_id,
	pay_type_id : pay_type_id,
	phone : phone,
	address : address,
	order_date_time : _fmt_order_date_time,
	user_id : user_id,
	};

	let _result = service_update_cust_order(cust_order).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_my_order_items(Json(order_item_request):Json<OrderItemRequest>) ->String {
    let cust_order_id = order_item_request.cust_order_id.unwrap_or_default();
    if cust_order_id == 0 {
        return r#"{  "rows": null,  "success": true}"#.to_string();
    }
	let order_items = service_list_my_order_items(cust_order_id).await;
	match order_items {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(order_items) => {
			let json = serde_json::to_string_pretty(&order_items).unwrap();
			//println!("{}", json);

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}
